package com.gdufe.studytogether.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gdufe.studytogether.domain.R;
import com.gdufe.studytogether.domain.pojo.Comment;
import com.gdufe.studytogether.domain.pojo.Competition;
import com.gdufe.studytogether.domain.pojo.User;
import com.gdufe.studytogether.mapper.CommentMapper;
import com.gdufe.studytogether.service.comment.CommentService;
import com.gdufe.studytogether.service.competition.CompetitionService;
import com.gdufe.studytogether.service.user.Impl.UserServiceImpl;
import com.gdufe.studytogether.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/competition")
public class CompetitionController {
    @Autowired
    CompetitionService competitionService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    CommentService commentService;
    @Autowired
    CommentMapper commentMapper;

    /**
     * 根据条件获取竞赛列表
     * @param pageSize
     * @param pageCurrent
     * @param competitionsName
     * @param status
     * @return
     */
    @GetMapping("/list")
    public R listCompetition(Long pageSize,Long pageCurrent,String competitionsName,String status){
        Page<Competition> competitionPage = new Page<>();
        if (pageSize==null){
            pageSize=20L;
        }
        if (pageCurrent==null){
            pageCurrent=1L;
        }
        competitionPage.setSize(pageSize);
        competitionPage.setCurrent(pageCurrent);
        QueryWrapper<Competition> competitionQueryWrapper = new QueryWrapper<>();
        competitionQueryWrapper.orderByDesc("createTime");
        competitionQueryWrapper.eq("status","0");

        if(competitionsName!=null&&!competitionsName.isEmpty()){
            competitionQueryWrapper.like("name",competitionsName);
        }
        if(status!=null&&!status.isEmpty()){
            switch (status){
                case "0": competitionQueryWrapper.ge("beginTime", LocalDate.now().toString());break;
                case "1": competitionQueryWrapper.le("beginTime", LocalDate.now().toString()).ge("endTime",LocalDate.now().toString());break;
                case "2": competitionQueryWrapper.le("endTime", LocalDate.now().toString());break;
            }
        }
        Page<Competition> page = competitionService.page(competitionPage,competitionQueryWrapper);
        List<Competition> records = page.getRecords();
        for (Competition competition : records) {
            Integer teacherId = competition.getUid();
            User teacher = userService.getById(teacherId);
            if(teacher==null){
                competition.setUsername("无");
            }else{
                competition.setUsername(teacher.getUsername());
            }
            LocalDate beginTime = competition.getBeginTime();
            LocalDate endTime = competition.getEndTime();
            LocalDate now = LocalDate.now();
            if(beginTime.isAfter(now)){
                competition.setStatus("0");
            }else if(endTime.isBefore(now)){
                competition.setStatus("2");
            }else{
                competition.setStatus("1");
            }
        }
        return R.ok(page);
    }

    @GetMapping("/getCidAndName")
    public R getCidAndName(){
        QueryWrapper<Competition> competitionQueryWrapper = new QueryWrapper<>();
        competitionQueryWrapper.eq("status","0");
        competitionQueryWrapper.le("beginTime", LocalDate.now().toString()).ge("endTime",LocalDate.now().toString());
        competitionQueryWrapper.or().ge("beginTime", LocalDate.now().toString());
        List<Competition> list = competitionService.list(competitionQueryWrapper);
        return R.ok(list);
    }

    /**
     * 发布竞赛信息
     * @param competition
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    public R addCompetition(@RequestBody Competition competition) throws Exception {
        Integer uid = UserThreadLocal.get();
        User user = userService.getById(uid);
        if (user.getRoleId()!=1&&user.getRoleId()!=3){
            return R.error("权限不足");
        }
        String name = competition.getName();
        if (StringUtils.isEmpty(name)){
            return R.error("赛事名称不能为空");
        }
        QueryWrapper<Competition> qw = new QueryWrapper<>();
        qw.eq("name",name);
        List<Competition> list = competitionService.list(qw);
        if (list!=null&&list.size()>0){
            return R.error("竞赛已存在");
        }
        String content = competition.getContent();
        if (StringUtils.isEmpty(content)){
            return R.error("赛事通知不能为空");
        }
        Integer teacherId = competition.getUid();
        if (teacherId==null){
            return R.error("负责教师不能为空");
        }
        User teacher = userService.getById(teacherId);
        if (teacher==null){
            return R.error("负责教师不存在");
        }
        LocalDate beginTime = competition.getBeginTime();
        LocalDate endTime = competition.getEndTime();
        if (beginTime==null){
            return R.error("开始时间不能为空");
        }
        if (endTime==null){
            return R.error("结束时间不能为空");
        }
        if (endTime.isBefore(beginTime)){
            return R.error("开始时间必须早于结束时间");
        }
        competition.setId(null);
        competition.setCreateTime(LocalDateTime.now());
        boolean save = competitionService.save(competition);
        if (!save){
            throw new Exception("添加竞赛信息失败");
        }
        return R.ok(null);
    }

    @PostMapping("/update")
    public R updateCompetition(@RequestBody Competition competition) throws Exception {
        Integer uid = UserThreadLocal.get();
        User user = userService.getById(uid);
        if (user.getRoleId()!=1&&user.getRoleId()!=3){
            return R.error("权限不足");
        }
        String name = competition.getName();
        if (StringUtils.isEmpty(name)){
            return R.error("赛事名称不能为空");
        }
        String content = competition.getContent();
        if (StringUtils.isEmpty(content)){
            return R.error("赛事通知不能为空");
        }
        Integer teacherId = competition.getUid();
        if (teacherId==null){
            return R.error("负责教师不能为空");
        }
        User teacher = userService.getById(teacherId);
        if (teacher==null){
            return R.error("负责教师不存在");
        }
        LocalDate beginTime = competition.getBeginTime();
        LocalDate endTime = competition.getEndTime();
        if (beginTime==null){
            return R.error("开始时间不能为空");
        }
        if (endTime==null){
            return R.error("结束时间不能为空");
        }
        if (endTime.isBefore(beginTime)){
            return R.error("开始时间必须早于结束时间");
        }
        competition.setStatus("0");
        boolean b = competitionService.updateById(competition);

        return R.ok();
    }

    @GetMapping("/delete")
    public R deleteCompetition(Integer id) throws Exception {
        Integer uid = UserThreadLocal.get();
        User user = userService.getById(uid);
        if (user.getRoleId()!=1&&user.getRoleId()!=3){
            return R.error("权限不足");
        }
        UpdateWrapper<Competition> qw = new UpdateWrapper<>();
        qw.eq("id",id);
        qw.set("status","1");
        competitionService.update(null,qw);

        return R.ok();
    }
}
